AppendToObject<T, K, V>
type-challenges 527
使用例
code:ts
type Test = { id: '1' };
type Result = AppendToObject<Test, 'value', 4>; // expected to be { id: '1', value: 4 }
定義例
{....A, ...B} と & を区別することを上手く扱わないといけない
Mapped Typesを使って1つのRecordとして定義する
code:1.ts
type AppendToObject<
T extends Record<string, unknown>,
K extends string,
V
= {
P in K | keyof T: P extends keyof T ? TP : V;
};
考え方としてはMerge<F, S>と近い
条件分岐のある最も無難な定義という感じ
MergeIntersections<T>を使う
code:2.ts
type AppendToObject<
T extends Record<string, unknown>,
U extends string,
V,
= MergeIntersections< T & { K in U: V; } >;
最も直観的
型引数を使って型変数を宣言するやつ
code:3.ts
type AppendToObject<
T extends Record<string, unknown>,
K extends string,
V,
R = T & { P in K: V },
= {
P in keyof R: RP;
};